//
//  WebNetworkTools+Extensions.swift
//  WeiBoApp
//
//  Created by CrazyHacker on 16/7/2.
//  Copyright © 2016年 CrazyHacker. All rights reserved.
//

import Foundation

/// 网络工具管理器的扩展类
extension WebNetworkTools {
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion: (list: [[String: AnyObject]]?, isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parametrs = ["since_id": "since_id",
                         "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        tokenRequest(URLString: urlString, parameters: parametrs) { (json, isSuccess) in
            
            // 从 json 中获取 statuses 字典数组
            // 如果 as? 失败，result = nil
            let result = json?["statuses"] as? [[String: AnyObject]]
            
            completion(list: result, isSuccess: isSuccess)
        }
    }
    
    /// 微博未读取数量
    func unreadCount(completion:(unReadCount:Int)->()) {
        
        guard let uid = userAccount.uid else {
         return
        }

        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let paramas = ["uid": uid]
        
        tokenRequest(URLString: urlString, parameters: paramas) { (json, isSuccess) in
            let result = json as? [String: AnyObject]
            let count = result?["status"] as? Int

            
            completion(unReadCount: count ?? 0)
        }
       
    }
    /// 加载授权令方法
    func loadAccessToken(code: String, completion:(isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id": WBAppleKey,
                          "client_secret": WBAppSecret,
                          "grant_type": "authorization_code",
                          "code": code,
                          "redirect_uri": WBReDirectURL]
        
        
        request(method: .POST, URLString: urlString, parameters: parameters) { (json, isSuccess) in
            // 直接使用字典设置 userAcount的属性
            self.userAccount.yy_modelSet(withJSON: json as? [String: AnyObject] ?? [:])
            
            self.loadUserInfo(completion: { (dict) in
                
                self.userAccount.yy_modelSet(with: dict)
                self.userAccount.saveUserAccount()
                // 完成回调
                completion(isSuccess: isSuccess)
               
            })
        }
    }
    
}

// MARK: - 加载用户信息
extension WebNetworkTools {
    /// 加载用户信息方法 返回用户信息字典
    func loadUserInfo(completion:(dict: [String: AnyObject])->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        //
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["uid": uid]
        
        // 发起网络请求
        tokenRequest(URLString: urlString, parameters: parameters) { (json, isSuccess) in
            completion(dict: (json as? [String: AnyObject]) ?? [:])
        }
    }
}

